<template>
  <div class="transport-plan-container">
    <div class="page-header">
      <div class="header-title">
        <h2>运输计划</h2>
        <span class="subtitle">管理和查看所有运输计划</span>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreatePlan">
          <el-icon><Plus /></el-icon>创建计划
        </el-button>
      </div>
    </div>

    <el-card class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="计划编号">
          <el-input v-model="filterForm.planNo" placeholder="输入计划编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
            <el-option label="计划中" value="planning"></el-option>
            <el-option label="执行中" value="executing"></el-option>
            <el-option label="已完成" value="completed"></el-option>
            <el-option label="已取消" value="cancelled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-container">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="全部计划" name="all"></el-tab-pane>
        <el-tab-pane label="计划中" name="planning"></el-tab-pane>
        <el-tab-pane label="执行中" name="executing"></el-tab-pane>
        <el-tab-pane label="已完成" name="completed"></el-tab-pane>
      </el-tabs>
      
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="planNo" label="计划编号" width="150"></el-table-column>
        <el-table-column prop="planName" label="计划名称" min-width="150"></el-table-column>
        <el-table-column prop="planDate" label="计划日期" width="120"></el-table-column>
        <el-table-column prop="orderCount" label="订单数量" width="100" align="center"></el-table-column>
        <el-table-column prop="vehicleCount" label="车辆数量" width="100" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="planner" label="计划人" width="120"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              @click="handleViewPlan(scope.row)"
              :disabled="scope.row.status === 'cancelled'"
            >
              查看
            </el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEditPlan(scope.row)"
              :disabled="['completed', 'cancelled'].includes(scope.row.status)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleCancelPlan(scope.row)"
              :disabled="['completed', 'cancelled'].includes(scope.row.status)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="table-footer">
        <div class="batch-actions" v-if="selectedRows.length > 0">
          <el-button size="small" type="danger" @click="handleBatchCancel">
            批量取消
          </el-button>
          <el-button size="small" type="warning" @click="handleBatchExport">
            批量导出
          </el-button>
        </div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 创建计划对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建运输计划"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="planForm"
        :model="planForm"
        :rules="planRules"
        label-width="120px"
      >
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="planForm.planName" placeholder="请输入计划名称"></el-input>
        </el-form-item>
        <el-form-item label="计划日期" prop="planDate">
          <el-date-picker
            v-model="planForm.planDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="计划描述" prop="description">
          <el-input
            v-model="planForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入计划描述"
          ></el-input>
        </el-form-item>
        
        <el-divider content-position="center">订单选择</el-divider>
        
        <el-form-item label="选择订单" prop="selectedOrders">
          <div class="order-selection">
            <div class="order-search">
              <el-input
                v-model="orderSearchKeyword"
                placeholder="搜索订单号或客户名称"
                clearable
                @input="searchOrders"
              >
                <template #append>
                  <el-button :icon="Search" @click="searchOrders"></el-button>
                </template>
              </el-input>
            </div>
            
            <el-table
              :data="availableOrders"
              border
              height="300px"
              @selection-change="handleOrderSelectionChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="orderNo" label="订单号" width="150"></el-table-column>
              <el-table-column prop="customer" label="客户名称" min-width="150"></el-table-column>
              <el-table-column prop="fromAddress" label="起始地" min-width="150" show-overflow-tooltip></el-table-column>
              <el-table-column prop="toAddress" label="目的地" min-width="150" show-overflow-tooltip></el-table-column>
              <el-table-column prop="expectedPickupTime" label="预计提货时间" width="180"></el-table-column>
            </el-table>
            
            <div class="selected-count">
              已选择 {{ planForm.selectedOrders.length }} 个订单
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPlanForm" :loading="submitting">
            确认创建
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'

const router = useRouter()

// 加载状态
const loading = ref(false)
const submitting = ref(false)

// 当前选中的标签页
const activeTab = ref('all')

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选表单
const filterForm = reactive({
  planNo: '',
  status: '',
  dateRange: []
})

// 表格数据
const tableData = ref([])

// 选中的行
const selectedRows = ref([])

// 创建计划对话框
const createDialogVisible = ref(false)

// 计划表单
const planForm = reactive({
  planName: '',
  planDate: '',
  description: '',
  selectedOrders: []
})

// 计划表单验证规则
const planRules = {
  planName: [
    { required: true, message: '请输入计划名称', trigger: 'blur' }
  ],
  planDate: [
    { required: true, message: '请选择计划日期', trigger: 'change' }
  ],
  selectedOrders: [
    { type: 'array', required: true, message: '请至少选择一个订单', trigger: 'change' }
  ]
}

// 表单引用
const planForm = ref(null)

// 订单搜索关键词
const orderSearchKeyword = ref('')

// 可用订单列表
const availableOrders = ref([
  {
    id: 1,
    orderNo: 'TMS-2025031401',
    customer: '北京物流科技有限公司',
    fromAddress: '北京市朝阳区建国路88号',
    toAddress: '上海市浦东新区张江高科技园区',
    expectedPickupTime: '2025-03-15 09:00:00'
  },
  {
    id: 2,
    orderNo: 'TMS-2025031402',
    customer: '上海贸易有限公司',
    fromAddress: '上海市黄浦区南京东路1号',
    toAddress: '北京市海淀区中关村大街1号',
    expectedPickupTime: '2025-03-16 10:00:00'
  },
  {
    id: 3,
    orderNo: 'TMS-2025031403',
    customer: '广州电子科技有限公司',
    fromAddress: '广州市天河区天河路385号',
    toAddress: '深圳市南山区科技园路1号',
    expectedPickupTime: '2025-03-15 14:00:00'
  },
  {
    id: 4,
    orderNo: 'TMS-2025031404',
    customer: '深圳科技有限公司',
    fromAddress: '深圳市福田区福田中心区',
    toAddress: '广州市番禺区市桥街道',
    expectedPickupTime: '2025-03-17 09:30:00'
  },
  {
    id: 5,
    orderNo: 'TMS-2025031405',
    customer: '杭州网络科技有限公司',
    fromAddress: '杭州市西湖区西湖文化广场',
    toAddress: '南京市鼓楼区中央路',
    expectedPickupTime: '2025-03-18 08:00:00'
  }
])

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'planning': 'info',
    'executing': 'warning',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    'planning': '计划中',
    'executing': '执行中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知'
}

// 处理查询
const handleSearch = () => {
  loading.value = true
  currentPage.value = 1
  fetchData()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.planNo = ''
  filterForm.status = ''
  filterForm.dateRange = []
  handleSearch()
}

// 处理标签页切换
const handleTabChange = (tab) => {
  if (tab.props.name === 'all') {
    filterForm.status = ''
  } else {
    filterForm.status = tab.props.name
  }
  handleSearch()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 处理选择行变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 处理查看计划
const handleViewPlan = (row) => {
  router.push(`/transport/plan/detail/${row.id}`)
}

// 处理编辑计划
const handleEditPlan = (row) => {
  router.push(`/transport/plan/edit/${row.id}`)
}

// 处理取消计划
const handleCancelPlan = (row) => {
  ElMessageBox.confirm(
    `确定要取消运输计划 "${row.planName}" 吗？`,
    '取消确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应用中应该调用API取消计划
    ElMessage.success('计划已取消')
    fetchData()
  }).catch(() => {
    // 取消操作
  })
}

// 处理批量取消
const handleBatchCancel = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个计划')
    return
  }
  
  ElMessageBox.confirm(
    `确定要取消选中的 ${selectedRows.value.length} 个计划吗？`,
    '批量取消确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应用中应该调用API批量取消计划
    ElMessage.success(`已取消 ${selectedRows.value.length} 个计划`)
    fetchData()
  }).catch(() => {
    // 取消操作
  })
}

// 处理批量导出
const handleBatchExport = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个计划')
    return
  }
  
  // 实际应用中应该调用API导出计划
  ElMessage.success(`已导出 ${selectedRows.value.length} 个计划`)
}

// 处理创建计划
const handleCreatePlan = () => {
  // 重置表单
  planForm.planName = ''
  planForm.planDate = ''
  planForm.description = ''
  planForm.selectedOrders = []
  
  createDialogVisible.value = true
}

// 搜索订单
const searchOrders = () => {
  // 实际应用中应该调用API搜索订单
  // 这里只做简单的前端筛选
  if (!orderSearchKeyword.value) {
    // 如果关键词为空，显示所有订单
    return
  }
  
  const keyword = orderSearchKeyword.value.toLowerCase()
  availableOrders.value = availableOrders.value.filter(order => 
    order.orderNo.toLowerCase().includes(keyword) || 
    order.customer.toLowerCase().includes(keyword)
  )
}

// 处理订单选择变化
const handleOrderSelectionChange = (selection) => {
  planForm.selectedOrders = selection
}

// 提交计划表单
const submitPlanForm = () => {
  planForm.value.validate((valid) => {
    if (valid) {
      if (planForm.selectedOrders.length === 0) {
        ElMessage.warning('请至少选择一个订单')
        return
      }
      
      submitting.value = true
      
      // 模拟API调用
      setTimeout(() => {
        submitting.value = false
        createDialogVisible.value = false
        
        ElMessage.success('运输计划创建成功')
        fetchData()
      }, 1500)
    } else {
      ElMessage.error('请完善表单信息')
      return false
    }
  })
}

// 获取数据
const fetchData = () => {
  loading.value = true
  
  // 模拟API调用
  setTimeout(() => {
    // 根据筛选条件和分页参数获取数据
    // 这里使用模拟数据
    tableData.value = [
      {
        id: 1,
        planNo: 'TP-2025031501',
        planName: '北京-上海运输计划',
        planDate: '2025-03-15',
        orderCount: 5,
        vehicleCount: 3,
        status: 'planning',
        planner: '张经理',
        createTime: '2025-03-14 15:30:22'
      },
      {
        id: 2,
        planNo: 'TP-2025031502',
        planName: '广州-深圳运输计划',
        planDate: '2025-03-16',
        orderCount: 3,
        vehicleCount: 2,
        status: 'executing',
        planner: '李经理',
        createTime: '2025-03-14 16:45:10'
      },
      {
        id: 3,
        planNo: 'TP-2025031503',
        planName: '上海-杭州运输计划',
        planDate: '2025-03-17',
        orderCount: 4,
        vehicleCount: 2,
        status: 'planning',
        planner: '王经理',
        createTime: '2025-03-14 17:20:35'
      },
      {
        id: 4,
        planNo: 'TP-2025031401',
        planName: '北京-天津运输计划',
        planDate: '2025-03-14',
        orderCount: 2,
        vehicleCount: 1,
        status: 'completed',
        planner: '赵经理',
        createTime: '2025-03-13 09:15:40'
      },
      {
        id: 5,
        planNo: 'TP-2025031402',
        planName: '武汉-长沙运输计划',
        planDate: '2025-03-14',
        orderCount: 3,
        vehicleCount: 2,
        status: 'cancelled',
        planner: '钱经理',
        createTime: '2025-03-13 10:30:15'
      }
    ]
    
    // 设置总数
    total.value = 50
    
    loading.value = false
  }, 500)
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.transport-plan-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.table-container {
  margin-bottom: 20px;
}

.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.batch-actions {
  display: flex;
  gap: 10px;
}

.order-selection {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.order-search {
  margin-bottom: 10px;
}

.selected-count {
  margin-top: 10px;
  text-align: right;
  color: #409EFF;
  font-size: 14px;
}
</style>
